package com.waterfairy.getipsocket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class GetIpSocketTool {
    private final static GetIpSocketTool getIpSocketTool = new GetIpSocketTool();

    private final int PORT_START = 51300;
    private final int MAX_NUM = 5;

    public static GetIpSocketTool getInstance() {
        return getIpSocketTool;
    }

    public void start() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                bindAndStart(PORT_START);
            }
        }.start();
    }

    private void bindAndStart(int port) {
        try {
            ServerSocket socketService = new ServerSocket(port);
            System.out.println("启动成功:" + port);
            while (true) {
                Socket socket = socketService.accept();
                InetAddress inetAddress = socket.getInetAddress();
                String hostAddress = inetAddress.getHostAddress();
                String html = "<html><head></head><body>您的本地上网IP: <h2>" + hostAddress + "</h2></body></html>";
                System.out.println("检测到客户端IP:" + hostAddress);
                String response = "HTTP/1.1 200 OK\r\n" +
                        "Content-Length: " + html.getBytes().length + "\r\n" +
                        "Content-Type: text/html;charset=UTF-8\r\n" +
                        "\r\n" +
                        html + "\r\n";

                OutputStream outputStream = socket.getOutputStream();
                outputStream.write(response.getBytes());
                outputStream.flush();
                socket.shutdownInput();
                socket.shutdownOutput();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (e instanceof BindException) {
                System.out.println("启动失败:" + port);
                if (port < PORT_START + MAX_NUM) {
                    System.out.println("尝试端口:" + (port + 1));
                    bindAndStart(port + 1);
                } else {
                    System.out.println("请设置更多的端口!");
                }
            }
        }
    }
}
